import ToolRequest from '@/base/newToolAxios';
import RequestOption from '@/base/RequestOption';
import { getActToolUrl } from '@/base/constant';
import axios from 'axios';
const tr = new ToolRequest();

export default class AttachmentDao {
  /**
   * 根据任务ID，为其添加附件,同时将文件保存在本地
   *
   * @param taskId    任务ID
   * @param creatorId 创建者ID
   * @param fileItems 文件列表
   */
  async upLoadTaskAttachment(fileItems, taskId, creatorId) {
    try {
      // 创建FormData对象
      const formData = new FormData();
      formData.append('file', fileItems);
      
      // 使用axios进行上传
      const result = await axios.post(
        getActToolUrl() +
          '&action=upLoadTaskAttachment' +
          '&taskId=' +
          taskId +
          '&creatorId=' +
          creatorId,
        formData,
        { 
          headers: { 'Content-Type': 'multipart/form-data' },
          timeout: 30000 // 设置30秒超时
        }
      );
      return result;
    } catch (error) {
      console.error('上传附件失败:', error);
      throw error;
    }
  }

  /**
   * 根据任务ID，返回与任务相关的所有附件
   *
   * @param taskId 任务ID
   * @return 附件列表
   */
  async findAttachmentsByTaskId(taskId) {
    const ro = new RequestOption();
    return await tr.get(
      getActToolUrl(),
      {
        action: 'findAttachmentsByTaskId',
        taskId: taskId
      },
      ro
    );
  }
  /**
   * 删除某个附件
   *
   * @param attachmentId 附件ID
   * @param attachmentUrl 附件地址
   */
  async deleteAttachmentByAttachmentId(attachmentId, attachmentUrl) {
    try {
      const ro = new RequestOption();
      ro.timeout = 30000; // 设置30秒超时
      return await tr.post(
        getActToolUrl(),
        {
          action: 'deleteAttachmentByAttachmentId',
          attachmentId: attachmentId,
          attachmentUrl: attachmentUrl || '' // 确保URL不为undefined
        },
        ro
      );
    } catch (error) {
      console.error('删除附件失败:', error);
      throw error;
    }
  }
}
